package com.example.controller;

import com.example.pojo.Ticket;
import com.example.service.TicketFeignService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ticket")
public class TicketController {
    @Autowired
    private TicketFeignService ticketFeignService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @HystrixCommand(fallbackMethod = "hystrixGetTicket")
    @GetMapping("/selectAll")
    public List<Ticket> getTicket() {
        System.out.println("1");
        List<Ticket> list = ticketFeignService.selectAll();
        if(list.size()==0){
            throw new RuntimeException("信息找不到");
        }
        return list;
    }

    public List<Ticket> hystrixGetTicket(){
        List<Ticket> list = new ArrayList<>();
        return list;
    }

    @PostMapping("/insertTicket")
    public boolean insertTicket(Ticket ticket) {
        return ticketFeignService.insertTicket(ticket);
    }
    @HystrixCommand(fallbackMethod = "hystrixGetTicket")
    @GetMapping("/getTicket/{id}")
    public Ticket getTicket(@PathVariable("id") long id){
        System.out.println("2");
        Ticket ticket = ticketFeignService.getTicket(id);
        if(ticket==null){
            throw new RuntimeException("信息查找不到");
        }
        return ticket;
    }

    public Ticket hystrixGetTicket(@PathVariable("id") long id){
        Ticket ticket = new Ticket();
        ticket.setId(id);
        ticket.setName("null");
        ticket.setDb("null");
        return ticket;
    }

    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> list = discoveryClient.getInstances("provider-ticket");
        for (ServiceInstance service:list){
            System.out.println(service.getHost()+"\t"+
                    service.getPort()+"\t"+
                    service.getUri()+"\t"+
                    service.getServiceId());
        }

        return this.discoveryClient;
    }


}

